package conversation

import (
	"gim-server/consts"
	"gim-server/errs"
	"gim-server/model"
	"gim-server/sdk"
	"gim-server/utils"
	"github.com/gin-gonic/gin"
)

type GetConversationListArgs struct {
	PageNo   int  `json:"page_no"`
	PageSize int  `json:"page_size"`
	All      bool `json:"all"`
}

func getConversationList(ctx *gin.Context) {
	var (
		err  error
		args = new(GetConversationListArgs)
	)
	if err = ctx.ShouldBindJSON(args); err != nil {
		utils.ERR(ctx, &utils.ErrArgs{
			Code: errs.ApiParamsErr,
			Err:  err,
		})
		return
	}
	db := sdk.DB(ctx)
	list := make([]*model.TbConversation, 0)
	sql := db.Where("from_uid = ?", ctx.GetString(consts.UID)).
		Order("mark_top desc, updated_at desc")
	if !args.All {
		if args.PageNo <= 0 {
			args.PageNo = 1
		}
		if args.PageSize <= 0 {
			args.PageSize = consts.PageSize
		}
		sql = sql.Offset((args.PageNo - 1) * args.PageSize).
			Limit(args.PageSize)
	}
	sql.Find(&list)
	if len(list) > 0 {
		for i, item := range list {
			msg := new(model.TbC2cMsgRecord)
			if err = db.Where("((from_uid = ? and to_uid = ?) or (from_uid = ? and to_uid = ?)) and del_uid not in ?",
				item.FromUID, item.ToUID, item.ToUID, item.FromUID, []string{"-1", ctx.GetString(consts.UID)}).
				Order("id desc").First(msg).Error; err == nil {
				list[i].LastMsg = msg
			}
		}
	}
	utils.SUC(ctx, utils.PageListDto{
		Arr:      list,
		PageNo:   args.PageNo,
		PageSize: args.PageSize,
	})
}
